package com.feicheng.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.base.batch.SaleBatch;
import com.feicheng.base.common.DaoConstant;
import com.feicheng.base.exception.SystemException;
import com.feicheng.base.result.Result;
import com.feicheng.entity.SaleOrderHeader;
import com.feicheng.entity.SaleOrderItem;
import com.feicheng.entity.StoreUser;
import com.feicheng.model.SaleOrderHeaderWithSaleOrderItem;
import com.feicheng.model.SaleOrderHeaderWithUser;
import com.feicheng.service.ISaleOrderHeaderService;
import com.feicheng.service.ISaleOrderItemService;
import com.feicheng.service.IStoreUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周启博
 * @since 2022-06-27
 */
@RestController
@RequestMapping("/sale_order_header")
public class SaleOrderHeaderController {

    /**
     * 销售订单用户详情页面
     * @param saleId (销售表主键)
     * @author shuoyu.qian
     * @return
     */

    /* 注入销售header的service */
    @Autowired
    ISaleOrderHeaderService iSaleOrderHeaderService;

    /* 注入销售item的service */
    @Autowired
    ISaleOrderItemService iSaleOrderItemService;

    /* 注入销售门店用户的service */
    @Autowired
    IStoreUserService iStoreUserService;

    @PostMapping("/sale_order/info")
    public Result selectSaleOrder(Integer saleId) {

        //当提成主键没有传的时候
        if (null == saleId) {
            //TODO
            throw new SystemException("主键不能为空！");
        }

        //根据条件查询数据
        SaleOrderHeader saleOrderHeader = iSaleOrderHeaderService.saleOrderHeader(saleId);

        //创建结果集
        JSONObject result = new JSONObject();

        //把查询到的数据装到结果集
        result.put(DaoConstant.SALE.TABLE,saleOrderHeader);

        //返回结果集
        return Result.success(result);
    }

    /**
     * 添加销售订单接口
     * @param saleOrderHeaderWithSaleOrderItem  业务参数
     * @author chunyu.zhao
     * @since 2022-07-06
     * @return
     */
    @PostMapping("/info")
    @Transactional
    public Result insertSaleOrder(
            @RequestBody SaleOrderHeaderWithSaleOrderItem saleOrderHeaderWithSaleOrderItem){

        System.out.println(saleOrderHeaderWithSaleOrderItem);
        //验证客户姓名不为空
        if (null == saleOrderHeaderWithSaleOrderItem.getCustomerName()) {
            //TODO
            throw new SystemException("客户姓名不能为空！");
        }

        //验证客户车架号不为空
        if (null == saleOrderHeaderWithSaleOrderItem.getCustomerFrameNo()) {
            //TODO
            throw new SystemException("客户车架号不能为空！");
        }

        //验证客户车牌号不为空
        if (null == saleOrderHeaderWithSaleOrderItem.getCustomerCarNo()) {
            //TODO
            throw new SystemException("客户车牌号不能为空！");
        }

        //验证门店编号不为空
        if (null == saleOrderHeaderWithSaleOrderItem.getStoreId()) {
            //TODO
            throw new SystemException("门店编号不能为空！");
        }

        //创建销售header表对象
        SaleOrderHeader saleOrderHeader = new SaleOrderHeader();

        //将客户姓名装进header表对象
        saleOrderHeader.setCustomerName(
                saleOrderHeaderWithSaleOrderItem.getCustomerName());

        //将客户电话装进header表对象
        saleOrderHeader.setCustomerTelephone(saleOrderHeaderWithSaleOrderItem.getCustomerTelephone());

        //将客户车架号装进header对象
        saleOrderHeader.setCustomerFrameNo(saleOrderHeaderWithSaleOrderItem.getCustomerFrameNo());

        //将客户车牌号装进header对象
        saleOrderHeader.setCustomerCarNo(saleOrderHeaderWithSaleOrderItem.getCustomerCarNo());

        //将销售员编号装进header对象
        saleOrderHeader.setUserId(saleOrderHeaderWithSaleOrderItem.getUserId());

        //将门店编号装进header对象
        saleOrderHeader.setStoreId(saleOrderHeaderWithSaleOrderItem.getStoreId());

        //将当前时间装进header对象
        saleOrderHeader.setDate(LocalDateTime.now());

        //生成销售订单批次号
        String batchNo = SaleBatch.getBatch(saleOrderHeaderWithSaleOrderItem.getUserId(),
                saleOrderHeaderWithSaleOrderItem.getStoreId());

        //将销售订单批次号装进header对象
        saleOrderHeader.setBatchNo(batchNo);

        //将销售员姓名装进header对象
        saleOrderHeader.setSalesperson(saleOrderHeaderWithSaleOrderItem.getSalesperson());

        //将订单状态装进header对象,默认为1
        saleOrderHeader.setState(DaoConstant.VALUE.DEFAULT_STATE);

        //向销售header表中添加数据
        iSaleOrderHeaderService.save(saleOrderHeader);


        System.out.println(saleOrderHeaderWithSaleOrderItem.getSaleOrderItem());
        //产品信息非空验证
        if (0 == saleOrderHeaderWithSaleOrderItem.getSaleOrderItem().length()){
            //TODO
            throw new SystemException("产品信息不能为空");
        }

        //将接收到的字符串转换为json数组
        JSONArray jsonArray =
                JSONArray.parseArray(saleOrderHeaderWithSaleOrderItem.getSaleOrderItem());

        //将json数组转换为list集合
        List<SaleOrderItem> saleOrderItemList =
                jsonArray.toJavaList(SaleOrderItem.class);

        //将数据放进集合中
        for (SaleOrderItem saleOrderItem : saleOrderItemList) {

            //验证item对象产品类型不能为空
            if(null == saleOrderItem.getProductType()){
                //TODO
                throw new SystemException("产品类型不能为空！");
            }

            //验证item对象产品名称不能为空
            if(null == saleOrderItem.getProductName()){
                //TODO
                throw new SystemException("产品名称不能为空！");
            }

            //验证item对象产品描述不能为空
            if(null == saleOrderItem.getDescription()){
                //TODO
                throw new SystemException("产品描述不能为空！");
            }

            //验证item对象销售数量不能为空
            if(null == saleOrderItem.getNum()){
                //TODO
                throw new SystemException("销售数量不能为空！");
            }

            //验证item对象汽车部位不能为空
            if(null == saleOrderItem.getProductName()){
                //TODO
                throw new SystemException("汽车部位不能为空！");
            }

            //将header编号放进item对象中
            saleOrderItem.setSaleId(saleOrderHeader.getSaleId());

        }

        //向item表中添加数据
        boolean insertItemFlag = iSaleOrderItemService.saveBatch(saleOrderItemList);

        //返回添加结果
        return Result.success(insertItemFlag);
    }

    /**
     *
     * @param current 当前页数
     * @param size    一页几条
     * @param saleOrderHeaderUser
     * @author   唐俊
     * @since 2022-07-05
     * @return
     */
    @PostMapping("/page/g")
    public Result PageConditionSelect (
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestBody SaleOrderHeaderWithUser saleOrderHeaderUser) {

        // 构建分页条件
        Page<SaleOrderHeaderWithUser> saleOrderHeaderUserPage
                = new Page<>(current,size);

        // 构建客户信息管理查询条件
        QueryWrapper<SaleOrderHeaderWithUser> saleOrderHeaderUserQueryWrapper
                = new QueryWrapper<>();

        /* 当参数中有顾客姓名的时候 */
        if (StringUtils.hasLength(saleOrderHeaderUser.getCustomerName())) {

            // 把顾客姓名作为查询条件
            saleOrderHeaderUserQueryWrapper.like(
                    DaoConstant.SALE_ORDER_HEADER.CUSTOMER_NAME,
                    saleOrderHeaderUser.getCustomerName());
        }

        /* 当参数中有顾客电话的时候 */
        if (StringUtils.hasLength(saleOrderHeaderUser.getCustomerTelephone())) {

            // 把顾客电话作为查询条件
            saleOrderHeaderUserQueryWrapper.like(
                    DaoConstant.SALE_ORDER_HEADER.CUSTOMER_TELEPHONE,
                    saleOrderHeaderUser.getCustomerTelephone());
        }

        /* 当参数中有顾客车牌号的时候 */
        if (StringUtils.hasLength(saleOrderHeaderUser.getCustomerCarNo())) {

            //把顾客车牌号作为查询条件
            saleOrderHeaderUserQueryWrapper.like(
                    DaoConstant.SALE_ORDER_HEADER.CUSTOMER_CAR_NO,
                    saleOrderHeaderUser.getCustomerCarNo());
        }

        /* 当参数中有顾客车架号的时候 */
        if (StringUtils.hasLength(saleOrderHeaderUser.getCustomerFrameNo())) {

            //把顾客车架号作为查询条件
            saleOrderHeaderUserQueryWrapper.like(
                    DaoConstant.SALE_ORDER_HEADER.CUSTOMER_FRAME_NO,
                    saleOrderHeaderUser.getCustomerFrameNo());
        }

        /* 当参数中有顾客订单号的时候 */
        if (StringUtils.hasLength(saleOrderHeaderUser.getBatchNo())) {

            //把顾客订单号作为查询条件
            saleOrderHeaderUserQueryWrapper.like(
                    DaoConstant.SALE_ORDER_HEADER.BATCH_NO,
                    saleOrderHeaderUser.getBatchNo());
        }

        /* 当参数中有顾客订单状态的时候 */
        if (null != saleOrderHeaderUser.getState()) {

            //把顾客订单状态作为条件
            saleOrderHeaderUserQueryWrapper.eq(
                    DaoConstant.SALE_ORDER_HEADER.STATE,
                    saleOrderHeaderUser.getState());
        }

        /* 当参数中有顾客订单开始时间的时候 */
        if (null != saleOrderHeaderUser.getStartDate()) {

            //把顾客订单开始时间作为条件
            saleOrderHeaderUserQueryWrapper.ge(
                    DaoConstant.SALE_ORDER_HEADER.DATE,
                    saleOrderHeaderUser.getStartDate());

        }

        /* 当参数中有顾客订单结束时间的时候 */
        if (null != saleOrderHeaderUser.getEndDate()) {

            //把顾客订单结束下时间作为条件
            saleOrderHeaderUserQueryWrapper.le(
                    DaoConstant.SALE_ORDER_HEADER.DATE,
                    saleOrderHeaderUser.getEndDate());
        }

        // 执行查询并返回结果
        return Result.success(
                iSaleOrderHeaderService.PageConditionSelect(
                        saleOrderHeaderUserPage,
                        saleOrderHeaderUserQueryWrapper
                ));
    }

    /**
     * 销售订单详情顾客信息修改服务
     * @param saleOrderHeader 用于接取顾客信息主键和顾客主键的对象
     * @return
     * @author yiming.chang
     */
    @PutMapping("/info")
    public Result updateCustomerInfo(
            @RequestBody SaleOrderHeader saleOrderHeader){

        /* 当顾客主键缺失时 */
        if (null == saleOrderHeader.getSaleId()) {
            // TODO
            throw new SystemException("缺少主键");
        }

        /* 当顾客姓名缺失时 */
        if (null == saleOrderHeader.getCustomerName()) {
            throw new SystemException("");
        }

        /* 当顾客电话缺失时 */
        if (null == saleOrderHeader.getCustomerTelephone()) {
            throw new SystemException("");
        }

        /* 当车架号缺失时 */
        if (null == saleOrderHeader.getCustomerFrameNo()) {
            throw new SystemException("");
        }

        /* 当车牌号缺失时 */
        if (null == saleOrderHeader.getCustomerCarNo()) {
            throw new SystemException("");
        }

        /* 当订单状态缺失时 */
        if (null == saleOrderHeader.getState()) {
            throw new SystemException("");
        }

        /* 返回结果 */
        return Result.success(iSaleOrderHeaderService.updateById(
                saleOrderHeader));
    }
}



